#include "luahandler.h"


#include "logger.h"
#include "main.h"
#include <string>
#include <assert.h>

using namespace std;
Luahandler::Luahandler(void) : mLuaPlusState(true)
{
	mCallback = NULL;
}

Luahandler::Luahandler( lua_State* lua )
{
	mLuaPlusState = LuaState::CastState(lua);
	mCallback = NULL;
}

Luahandler::Luahandler( LuaStateOwner state ) : mLuaPlusState(state.Get()), mCallback(NULL)
{
}

Luahandler::Luahandler( LuaState* state ) : mLuaPlusState(state), mCallback(NULL)
{
}

Luahandler::~Luahandler(void)
{
	LuaState::Destroy(mLuaPlusState);
}

int Luahandler::DoFile( const wchar_t* filename )
{
	wstring wsfilename(filename);
	string sfilename = ws2s(wsfilename);
	logger->Log("Do lua file: %s",sfilename.c_str());
	//mLuaPlusState->OpenLibs();
	//ExportFunctionToLua();
	int ret = mLuaPlusState->DoFile(sfilename.c_str());
	return ret;
}

int Luahandler::GetGlobalInt( const char* name )
{
	LuaObject var = mLuaPlusState->GetGlobal(name);
	if (var.IsInteger())
	{
		return var.GetInteger();
	} 
	else
	{
		if (var.IsConvertibleToInteger())
		{
			return var.ToInteger();
		}
	}

	logger->Log("Error in Luahandler::GetGlobalInt()");
	assert(false);
	return 0;
}

double Luahandler::GetGlobalDouble( const char* name )
{
	LuaObject var = mLuaPlusState->GetGlobal(name);
	if (var.IsNumber())
	{
		return var.GetNumber();
	} 
	else
	{
		if (var.IsConvertibleToNumber())
		{
			return var.ToNumber();
		}
	}
	
	logger->Log("Error in Luahandler::GetGlobalDouble()");
	assert(false);
	return 0;
}

string Luahandler::GetGlobalString( const char* name )
{
	LuaObject var = mLuaPlusState->GetGlobal(name);
	if (var.IsString())
	{
		return var.GetString();
	} 
	else
	{
		if (var.IsConvertibleToString())
		{
			return var.ToString();
		}
	}

	logger->Log("Error in Luahandler::GetGlobalString()");
	assert(false);
	return 0;
}

bool Luahandler::GetGlobalBool( const char* name )
{
	LuaObject var = mLuaPlusState->GetGlobal(name);
	if (var.IsBoolean())
	{
		return var.GetBoolean();
	}
	logger->Log("Error in Luahandler::GetGlobalBool()");
	assert(false);
	return 0;
}

void Luahandler::SetExportFunction( void(*callback)(lua_State* lua) )
{
	mCallback = callback;
}

void Luahandler::ExportFunctionToLua( void )
{
	if (mCallback)
	{
		mCallback(mLuaPlusState->GetCState());
	}
}

LuaStateOwner& Luahandler::GetState()
{
	return mLuaPlusState;
}
